package com.ctrip.ec.api.admin.controller.after;
import com.ctrip.ec.api.admin.model.after.AfterSalesModel;
import com.ctrip.ec.api.admin.model.query.QueryModel;
import com.ctrip.ec.biz.dao.order.OrderDao;
import com.ctrip.ec.biz.dao.order.OrderGoodsDao;
import com.ctrip.ec.biz.entity.after.AfterSalesStatus;
import com.ctrip.ec.biz.entity.after.AfterSalesType;
import com.ctrip.ec.biz.entity.order.OrderEntity;
import com.ctrip.ec.biz.entity.order.OrderGoodsEntity;
import com.ctrip.ec.biz.entity.order.OrderStatus;
import com.ctrip.ec.dal.PagerSetting;
import com.ctrip.ec.api.admin.common.RequestContext;
import com.ctrip.ec.biz.dao.after.AfterSalesDao;
import com.ctrip.ec.biz.entity.after.AfterSalesEntity;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("afterSales")
public class AfterSalesController {
    @Autowired
    private AfterSalesDao afterSales;

    @Autowired
    private OrderDao order;

    @Autowired
    private OrderGoodsDao orderGoods;

    @PostMapping("list")
    public List<AfterSalesEntity> list(@RequestBody QueryModel model) throws  SQLException{
        PagerSetting setting = model.build();
        List<AfterSalesEntity> list = afterSales.list(setting);
        RequestContext.setResponseHeaderCount(setting.getRecordCount());
        return list;
    }

    @GetMapping("detail/{id}")
    public AfterSalesModel detail(@PathVariable Long id) throws SQLException {
        AfterSalesEntity entity =  afterSales.entity(id);

        AfterSalesModel model = new AfterSalesModel(entity);

        OrderGoodsEntity orderGoodsEntity = orderGoods.entity(entity.getOrderGoodsId());
        OrderEntity orderEntity = order.entity(entity.getOrderId());

        model.setOrder(orderEntity);
        model.setOrderGoods(orderGoodsEntity);

        return model;
    }

//    @PostMapping("save")
//    public  Long save(@RequestBody AfterSalesEntity entity) throws SQLException {
//        afterSales.save(entity);
//        return entity.getId();
//    }

    @PostMapping("approve")
    public  void approve(@RequestBody Map<String,Object> map) throws SQLException {
        Long id = Long.parseLong(map.get("id").toString());
        String remark=map.get("remark").toString();
        String amount = map.get("amount").toString();

        AfterSalesEntity entity = afterSales.entity(id);

        OrderGoodsEntity orderGoodsEntity = orderGoods.entity(entity.getOrderGoodsId());

        afterSales.getDb().begin();
        try{
            entity.setRemark(remark);
            entity.setStatus(AfterSalesStatus.审核通过.ordinal());
            if(entity.getType() == AfterSalesType.退货.ordinal()){
                if(amount != null){
                    entity.setAmount(new BigDecimal(amount));
                }
            }
            entity.setAuditId(RequestContext.getUserId());
            entity.setAuditTime(new Timestamp(System.currentTimeMillis()));
            afterSales.save(entity);

            orderGoodsEntity.setInAfterSales(false);
            orderGoodsEntity.setAfterSalesStatus(AfterSalesStatus.审核通过.ordinal());
            if(entity.getType() == AfterSalesType.退货.ordinal()){
                orderGoodsEntity.setBackAmount(orderGoodsEntity.getBackAmount().add(entity.getAmount()));
                orderGoodsEntity.setBackNum(orderGoodsEntity.getBackNum() + entity.getNum());
                //需要保存一下次，不然后面从数据库取不到
                orderGoods.save(orderGoodsEntity);

                //代购费需要被扣除，用于统计,增加order表的退款总额
                OrderEntity orderEntity = order.entity(orderGoodsEntity.getOrderId());
                BigDecimal subAgencyAmount = orderGoodsEntity.getAgencyPrice().multiply(new BigDecimal(entity.getNum()));
                orderEntity.setAgencyAmount(orderEntity.getAgencyAmount().subtract(subAgencyAmount));
                orderEntity.setBackAmount(orderEntity.getBackAmount().add(entity.getAmount()));

                order.save(orderEntity);

                //如果此订单下所有商品都被退款，则此订单取消
                List<OrderGoodsEntity> tmpList = orderGoods.listByOrderId(orderGoodsEntity.getOrderId());
                boolean canCancel = true;
                for(OrderGoodsEntity tmp  : tmpList){
                    if(!tmp.getBackNum().equals(tmp.getBuyNum())){
                        canCancel = false;
                        break;
                    }
                }
                if(canCancel){
                    List<OrderEntity> list = new ArrayList<>();
                    list.add(orderEntity);
                    order.cancel(list);
                }
            }
            orderGoods.save(orderGoodsEntity);
            afterSales.getDb().commit();
        }catch (Exception ex){
            afterSales.getDb().rollback();
            throw ex;
        }

    }

    @PostMapping("deny")
    public  void deny(@RequestBody Map<String,Object> map) throws SQLException {
        Long id = Long.parseLong(map.get("id").toString());
        String remark=map.get("remark").toString();

        AfterSalesEntity entity = afterSales.entity(id);

        OrderGoodsEntity orderGoodsEntity = orderGoods.entity(entity.getOrderGoodsId());

        afterSales.getDb().begin();
        try{
            entity.setRemark(remark);
            entity.setStatus(AfterSalesStatus.审核驳回.ordinal());
            afterSales.save(entity);

            orderGoodsEntity.setInAfterSales(false);
            orderGoodsEntity.setAfterSalesStatus(AfterSalesStatus.审核驳回.ordinal());


            orderGoods.save(orderGoodsEntity);

            afterSales.getDb().commit();
        }catch (Exception ex){
            afterSales.getDb().rollback();
        }
    }

    @PostMapping("delete")
    public  void delete(@RequestBody List<Long> ids) throws SQLException {
        afterSales.delete(ids);
    }
    @PostMapping("erase")
    public void erase(@RequestBody List<Long> ids) throws  SQLException{
        afterSales.erase(ids);
    }

    @PostMapping("unerase")
    public  void unerase(@RequestBody List<Long> ids) throws  SQLException{
        afterSales.unerase(ids);
    }
}
